package pers.sloera.leetcode.editor.cn;

import java.util.BitSet;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 保证文件名唯一
 *
 * @author sloera
 * @date 2023-03-03 19:24:31
 */
class MakingFileNamesUnique {
    public static void main(String[] args) {
        Solution solution = new MakingFileNamesUnique().new Solution();
        // System.out.println(solution.getFolderNames(new String[]{"gta", "gta(1)", "gta", "avalon"}));
        // System.out.println(solution.getFolderNames(new String[]{"kingston(0)", "kingston", "kingston"}));
        System.out.println(solution.getFolderNames(new String[]{"kingston(2)", "kingston", "kingston"}));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public Pattern numberPattern = Pattern.compile("^(.*)\\((\\d+)\\)$");

        public String[] getFolderNames(String[] names) {
            String[] ret = new String[names.length];
            Map<String, BitSet> countMap = new HashMap<>();
            for (int i = 0; i < names.length; i++) {
                String name = names[i];
                if (countMap.containsKey(name)) {
                    int count = countMap.get(name).nextClearBit(0);
                    // 自身重复
                    if (count != 0) {
                        ret[i] = name + "(" + count + ")";
                        countMap.computeIfAbsent(ret[i], x -> new BitSet()).set(countMap.computeIfAbsent(ret[i], x -> new BitSet()).nextClearBit(0));
                        countMap.get(name).set(count);
                    } else {
                        // 括号前重复
                        ret[i] = name;
                        countMap.get(ret[i]).set(count);
                    }
                    // 重复的key和新增的key都放入计数中
                } else {
                    ret[i] = name;
                    countMap.computeIfAbsent(ret[i], x -> new BitSet()).set(0);
                }
                // 计算(前的数量
                if (ret[i].contains("(")) {
                    Matcher matcher = numberPattern.matcher(ret[i]);
                    // k为正整数，所以为0时，可以不占用key的位置
                    if (matcher.matches() && Integer.parseInt(matcher.group(2)) != 0) {
                        countMap.computeIfAbsent(matcher.group(1), x -> new BitSet()).set(Integer.parseInt(matcher.group(2)));
                    }
                }
            }
            return ret;
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)

}
